using AutoMapper;
using B.S.NewMedical.Api.Write.Application.Command.ContentManagement.Carousel;
using B.S.NewMedical.Domain.Hospital;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;

namespace B.S.NewMedical.Api.Write.Application.Handler.ContentManagement.Carousel
{
    /// <summary>
    /// 更新轮播图命令处理器
    /// </summary>
    public class UpdateCarouselCommandHandler : IRequestHandler<UpdateCarouselCommand, bool>
    {
        private readonly IMapper _mapper;
        private readonly IBaseRepository<CarouselModel> _carouselRepository;

        public UpdateCarouselCommandHandler(IMapper mapper, IBaseRepository<CarouselModel> carouselRepository)
        {
            _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
            _carouselRepository = carouselRepository ?? throw new ArgumentNullException(nameof(carouselRepository));
        }

        /// <summary>
        /// 处理更新轮播图命令
        /// </summary>
        /// <param name="request">更新轮播图命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>是否更新成功</returns>
        public async Task<bool> Handle(UpdateCarouselCommand request, CancellationToken cancellationToken)
        {
            // 获取现有实体
            var existingCarousel = await _carouselRepository.GetValue(request.Id);
            if (existingCarousel == null || existingCarousel.IsDeleted)
            {
                return false;
            }

            // 使用 AutoMapper 更新实体属性
            _mapper.Map(request, existingCarousel);

            // 设置更新时间
            existingCarousel.UpdateTime = DateTime.Now;

            // 保存更新
            await _carouselRepository.UpdateAsync(existingCarousel);
            return true;
        }
    }
}